package com.bybops.ui.activity.account

import android.Manifest
import android.os.Bundle
import android.text.TextUtils
import android.view.View
import baseproject.com.mybaseproject.mvp.contract.LoginContract
import baseproject.com.mybaseproject.mvp.presenter.LoginPresenterImpl
import baseproject.com.mybaseproject.ui.base.BaseMvpActivity
import baseproject.com.mybaseproject.utils.ActivityUtils
import baseproject.com.mybaseproject.utils.scheduler.RxUtils
import com.bybops.R
import com.bybops.app.AppConstant
import com.bybops.app.MyApplication
import com.bybops.model.bean.User
import com.bybops.ui.activity.MainActivity
import com.bybops.utils.AndroidBug5497Workaround
import com.bybops.utils.GsonUtils
import com.bybops.utils.SPUtils
import io.reactivex.functions.Consumer
import kotlinx.android.synthetic.main.activity_login.*



class LoginActivity : BaseMvpActivity<LoginContract.LoginView, LoginPresenterImpl>(), LoginContract.LoginView {


    override var mPresenter = LoginPresenterImpl()

    override fun getLayoutId(): Int? {
        return R.layout.activity_login
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        AndroidBug5497Workaround.assistActivity(this)
        initView()
    }

    private fun initView() {
        //回显员工编号
        loginUserName.setText(MyApplication.instance?.mUser?.telephone)
        //登陆按钮点击事件
        RxUtils.rxClick(loginButton, object : RxUtils.OnClickInterf {
            override fun onViewClick(view: View) {
                if (TextUtils.isEmpty(loginUserName.text.toString().trim())) {
                    showToast("用户名为空")
                    return
                }
                if (TextUtils.isEmpty(loginPassWord.text.toString().trim())) {
                    showToast("密码为空")
                    return
                }
                //读取手机状态申请
                rxPermissions.request(Manifest.permission.READ_PHONE_STATE)
                        .subscribe(Consumer {
                            if (it) {
                                mPresenter.login()
                            }
                        })
            }
        })
    }

    override fun getUserName(): String {
        return loginUserName.text.toString().trim()
    }

    override fun getPassword(): String {
        return loginPassWord.text.toString().trim()
    }

    /**
     * 登录成功
     */
    override fun loginSucess(user: User) {
        //设置用户信息
        MyApplication.instance?.setUser(user)
        //保存用户名
        SPUtils.put(AppConstant.Access_Token, user.access_token)
        SPUtils.put(AppConstant.userInfo, GsonUtils.toJsonWithSerializeNulls(user))
        ActivityUtils.startActivityAndFinish(this@LoginActivity, MainActivity::class.java)
    }

    /**
     * 登录失败
     */
    override fun loginFailed(errorMsg: String) {
        showToast(errorMsg)
    }



}